package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.TalkListData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zhangshuai on 15/10/21.
 */
public class GetTalkNewMsg extends CcMsgStructure {

    private Message mmCallback;
    private Context mContext;

    public GetTalkNewMsg(Message callback, Context context) {
        mmCallback = callback;
        mContext = context;
    }

    @Override
    public void onReceive(JSONObject data) {
        TalkListData talkListData = new TalkListData();
        try {
            JSONObject item = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            if(item.has("talk_id")){
                talkListData.talkId = item.getString("talk_id");
            }
            if(item.has("uname")){
                talkListData.uName = item.getString("uname");
            }
            if(item.has("uid")){
                talkListData.uId = item.getString("uid");
            }
            if(item.has("uimg")){
                talkListData.uImage = item.getString("uimg");
            }
            if(item.has("msg_count")){
                talkListData.msgCount = item.getString("msg_count");
            }
        } catch (JSONException e) {
            Log.d("talkListData", e.toString());
            e.printStackTrace();
        }

        if (mmCallback != null) {
            mmCallback.obj = talkListData;
            mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
            return;
        }
    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }
}
